package com.excuse.excusebuilder.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.excuse.excusebuilder.R;
import com.excuse.excusebuilder.bean.User;
import com.excuse.excusebuilder.commen.util.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by U-nookia on 2017/4/21.
 */

public class SignInActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.name_edt)
    EditText nameEdt;
    @BindView(R.id.password_edt)
    EditText passwordEdt;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.sign_up)
    TextView signUp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);
        ButterKnife.bind(this);

        checkIfSignIn();

        toolbar.setTitle("登录");
        toolbar.setTitleTextColor(getResources().getColor(R.color.md_white_1000));
    }

    private void checkIfSignIn() {
        if (BmobUser.getCurrentUser()!=null){
            startActivity(new Intent(SignInActivity.this, MainActivity.class));
            finish();
        }
    }

    @OnClick(R.id.btn)
    public void onViewClicked() {
        String name = nameEdt.getText().toString();
        String password = passwordEdt.getText().toString();
        if (name.equals("") || password.equals("")) {
            ToastUtil.makeShortToast(this, "输入不能为空");
            return;
        }
        User user = new User();
        user.setUsername(name);
        user.setPassword(password);
        user.login(new SaveListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e != null) {
                    ToastUtil.makeShortToast(SignInActivity.this, e.toString());
                    return;
                }
                startActivity(new Intent(SignInActivity.this, MainActivity.class));
                finish();
                ToastUtil.makeShortToast(SignInActivity.this,"登录成功");
            }
        });
    }

    @OnClick(R.id.sign_up)
    public void onSignUpClicked() {
        startActivity(new Intent(SignInActivity.this,SignUpActivity.class));
        finish();
    }
}
